<?php
class Auth {
	
	public static function init($core) {
		if ( false === ($auth = JBlog::cookie('auth')) ) return false;
		list($userid, $password) = explode("\t", self::authcode($auth, 'DECODE'));
		if ( is_numeric($userid) ) {
			$user = M('User', $userid);
			if ($user->exists) {
				if ($password == md5($user->password.$user->userkey.$_SERVER['HTTP_USER_AGENT'])) {
					$core->userid = $user->id;
					$core->user = $user;
				}
			}
		}
	}

	public static function set($userid, $password, $expire = 0) {
		$userkey = String::random(10);
		$cookie = self::authcode("{$userid}\t".md5($password.$userkey.$_SERVER['HTTP_USER_AGENT']));
		JBlog::cookie('auth', $cookie, $expire);
		$user = M('User', $userid);
		$user->userkey = $userkey;
		$user->save();
		return $userkey;
	}
	
	public static function authcode($string, $method = 'ENCODE') {
		$key = substr(md5($_SERVER['HTTP_USER_AGENT'].JBlog::config('JBLOG_KEY')),-10);
		$keylen = strlen($key);
		$strlen = strlen($string);
		$string = $method == 'DECODE' ? base64_decode($string) : $string;
		$code = '';
		for ( $i=0; $i<$strlen; $i++ ) {
			$k = $i % $keylen;
			$code .= $string{$i} ^ $key{$k};
		}
		return ($method == 'ENCODE' ? base64_encode($code) : $code);
	}
	
	public static function destory() {
		JBlog::cookie('auth', '', -1);
	}
}
?>